<template>
  <transition name='fade'>
    <musiclist
    :bgImage='bgImage'
    :title='title'
    :songs='songs'
    :rank='rank'
    @selectItem='selectItem'
    @randomItem='randomItem'
    >
    </musiclist>
  </transition>
</template>
<script>
  import { mapGetters, mapActions } from 'vuex';
  import musiclist from 'comp/music-list/musicList';
  import { getMusicList } from '@/api/rank';
  import { createSong } from '@/common/js/song';

  export default {
    name: 'toplist',
    components: {
      musiclist,
    },
    data() {
      return {
        songs: [],
        rank: true,
      };
    },
    computed: {
      bgImage() {
        if (this.songs.length) {
          return this.songs[0].image;
        }
        return '';
      },
      title() {
        return this.toplist.topTitle;
      },
      ...mapGetters(['toplist']),
    },
    methods: {
      selectItem({ index }) {
        this.selectPlay({ list: this.songs, index });
      },
      randomItem() {
        this.randomPlay({ list: this.songs });
      },
      _getMusicList() {
        if (!this.toplist.id) {
          this.$router.push('/rank');
          return;
        }
        getMusicList(this.toplist.id).then((res) => {
          this.songs = this._normalizeSongs(res.songlist);
        });
      },
      _normalizeSongs(list) {
        const ret = [];
        list.forEach((item) => {
          const musicData = item.data;
          if (musicData.songid && musicData.albummid) {
            ret.push(createSong(musicData));
          }
        });
        return ret;
      },
      ...mapActions(['selectPlay', 'randomPlay']),
    },
    created() {
      this._getMusicList();
    },
  };
</script>
<style lang='stylus' scoped>
.fade-enter-active, .fade-leave-active {
  transition all .5s
}
.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
  opacity 0
  transform translate3D(100%, 0, 0);
}
</style>
